<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">录入数据</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="cropTypeList"
      border
      highlight-current-row
      style="width: 100%;"
    >
      <!-- <el-table-column type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="名称">
              <span>{{ row.name }}</span>
            </el-form-item>
            <el-form-item label="简介">
              <span>{{ row.introduction }}</span>
            </el-form-item>
            <el-form-item label="图片">
              <el-image
                class="image"
                :src="imgUrl + '/' + row.image"
                :preview-src-list="[imgUrl + '/' + row.image]"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column> -->
      <el-table-column label="编号" align="center" width="90px" type="index" :index="indexMethod" />
      <el-table-column label="名称" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" :show-overflow-tooltip="true">
        <template slot-scope="{row}">
          <span>{{ row.introduction }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100px"
        class-name="small-padding fixed-width"
        width="150px"
      >
        <template slot-scope="{row}">
          <el-button type="success" size="mini" @click="detailData(row.cropTypeId)">详情</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row.cropTypeId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="作物品种" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="品种简介" prop="itdt">
          <el-input v-model="temp.itdt" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item label="企业" prop="entId">
          <el-select
            v-model="temp.entId"
            class="full-width"
            placeholder="请选择"
            :disabled="entFlag"
            @change="handleEntChange"
          >
            <el-option
              v-for="item in entOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="基地" prop="siteId">
          <el-select
            v-model="temp.siteId"
            class="full-width"
            placeholder="请选择"
            :disabled="siteFlag"
            @change="handleSiteChange"
          >
            <el-option
              v-for="item in siteOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地块" prop="placeId">
          <el-select
            v-model="temp.placeId"
            class="full-width"
            placeholder="请选择"
            :disabled="placeFlag"
          >
            <el-option
              v-for="item in placeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="品种图片" prop="image">
          <el-upload
            ref="uploadImage"
            :action="uploadFileUrl"
            name="file"
            :data="data"
            :auto-upload="false"
            list-type="picture-card"
            :limit="1"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          :disabled="entFlag || siteFlag || placeFlag"
          type="primary"
          @click="dialogStatus==='add'?addData():modifiedData()"
        >确定</el-button>
      </div>
    </el-dialog>

    <type-detail-dialog
      :detail-dialog="detailDialog"
      :data="cropTypeData"
      @close-dialog="detailDialog = false"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { queryCropType, deleteCropType, addCropType, queryCropTypeDeatil } from '@/api/cropType'
import { queryEnterprise, getAllEnterprise } from '@/api/enterprise'
import { queryBase, queryPlantationByEnt } from '@/api/base'
import { queryPlace } from '@/api/place'
import TypeDetailDialog from './components/TypeDetailDialog'
import elDragDialog from '@/directive/el-drag-dialog'
import store from '@/store'
import { cropMixin } from '@/mixins/cropMixin'

export default {
  name: 'CropType',
  components: { TypeDetailDialog },
  directives: { elDragDialog },
  mixins: [cropMixin],
  data() {
    const IMAGE_FILE_NAME = 'cropTypeImage'
    return {
      category: 'crop_type',
      tableKey: 0,
      cropTypeList: [],
      listLoading: true,
      listQuery: {
        cropTypeId: -1,
        account: store.getters.token
      },
      data: {
        account: store.getters.token,
        path: IMAGE_FILE_NAME
      },
      temp: {
        name: '',
        itdt: '',
        image: '',
        entId: -2,
        siteId: -2,
        placeId: -2,
        account: store.getters.token
      },
      rules: {
        name: [
          {
            required: true,
            message: '请填写作物品种',
            trigger: 'change'
          }
        ],
        itdt: [
          {
            type: 'string',
            required: true,
            message: '请填写品种简介',
            trigger: 'change'
          }
        ],
        image: [
          {
            type: 'string',
            required: true,
            message: '请选择作物品种图片',
            trigger: 'change'
          }
        ]
      },
      dialogStatus: '',
      dialogFormVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      textMap: {
        add: '录入数据'
      },
      entOptions: [],
      siteOptions: [],
      placeOptions: [],
      allSites: [],
      imgUrl: process.env.VUE_APP_BASE_IMAGE_API + IMAGE_FILE_NAME,
      uploadFileUrl: store.getters.uploadFileUrl,
      detailDialog: false,
      cropTypeData: null
    }
  },
  computed: {
    ...mapGetters([
      'role'
    ]),
    entFlag() {
      return this.temp.entId === -1
    },
    siteFlag() {
      return this.temp.siteId === -2
    },
    placeFlag() {
      return this.temp.placeId === -1
    }
  },
  async created() {
    this.fetchData()
    await this.getEnts()
  },
  methods: {
    async detailData(cropTypeId) {
      this.detailDialog = true
      const res = await queryCropTypeDeatil({ cropTypeId })
      const data = res.cropType[0]
      data.image = this.imgUrl + '/' + data.image
      data.entName = res.ent[0].entName
      data.plantationName = res.plantation[0].siteName
      data.placeName = res.place[0].placeName
      this.cropTypeData = data
    },
    getEnts() {
      return new Promise((resolve, reject) => {
        if (this.role === '0') {
          this.getAllEnterprise()
        } else {
          this.queryEnts()
        }
        resolve()
      })
    },
    async queryEnts() {
      const res = await queryEnterprise({
        account: store.getters.token,
        limit: -1,
        page: -1
      })
      await this.handleEntsData(res.enterprise)
    },
    async getAllEnterprise() {
      const res = await getAllEnterprise({
        limit: -1,
        page: -1
      })
      await this.handleEntsData(res.enterprise)
    },
    handleEntsData(ents) {
      return new Promise((resolve, reject) => {
        this.entOptions = ents.map(item => {
          return {
            label: item.entName,
            value: item.entId
          }
        })
        if (this.entOptions.length === 0) {
          this.entOptions.push({
            label: '暂无企业',
            value: -1
          })
        }
        this.temp.entId = this.entOptions[0].value
        this.getSites()
        resolve()
      })
    },
    async getSites() {
      const res = await queryPlantationByEnt({
        entId: this.temp.entId
      })
      this.handleSitesData(res.sites)
    },
    handleSitesData(sites) {
      return new Promise((resolve, reject) => {
        this.allSites = sites.map(item => {
          return {
            label: item.siteName,
            value: item.siteId,
            entId: item.entId
          }
        })
        this.siteOptions = this.allSites.filter(item => {
          return item.entId === this.temp.entId
        })
        if (this.siteOptions.length === 0) {
          this.siteOptions.push({
            label: '暂无基地',
            value: -2
          })
        }
        this.temp.siteId = this.siteOptions[0].value
        this.getPlaces()
      })
    },
    getPlaces() {
      queryPlace({
        placeId: -1,
        siteId: this.temp.siteId,
        limit: -1,
        pageNumber: 0,
        type: ''
      })
        .then(response => {
          this.placeOptions = response.places.map(item => {
            return {
              label: item.placeName,
              value: item.placeId
            }
          })
          if (this.placeOptions.length === 0) {
            this.placeOptions.push({
              label: '暂无地块',
              value: -1
            })
          }
          this.temp.placeId = this.placeOptions[0].value
        })
        .catch(error => {
          this.placeOptions = [{
            label: '暂无地块',
            value: -1
          }]
          this.temp.placeId = this.placeOptions[0].value
          console.log(error)
        })
    },
    handleEntChange(entId) {
      this.temp.entId = entId
      this.getSites()
    },
    handleSiteChange(siteId) {
      this.temp.siteId = siteId
      this.getPlaces()
    },

    resetTemp() {
      this.temp = {
        name: '',
        itdt: '',
        image: '',
        entId: this.temp.entId,
        siteId: this.temp.siteId,
        placeId: this.temp.placeId,
        account: store.getters.token
      }
    },
    handleAdd() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$refs['uploadImage'].submit()
        }
      })
    },
    handleDelete(id) {
      this.$msgbox
        .confirm('您确定要删除这条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          deleteCropType({ cropTypeId: id })
            .then(response => {
              const index = this.cropTypeList.findIndex(
                v => v.cropTypeId === id
              )
              this.cropTypeList.splice(index, 1)
              this.$notify({
                title: '提示',
                message: '删除成功！',
                type: 'success',
                duration: 2000
              })
            })
            .catch(error => {
              console.log(error)
              this.$notify({
                title: '提示',
                message: '删除失败！',
                type: 'error',
                duration: 2000
              })
            })
        })
    },
    handleSuccess(response, file, fileList) {
      fileList.pop()
      this.temp.image = response.fileName
      addCropType(this.temp).then(response => {
        const tempItem = this.temp
        tempItem.introduction = tempItem.itdt
        this.cropTypeList.unshift(tempItem)
        this.dialogFormVisible = false
        this.$notify({
          title: '提示',
          message: '添加成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      if (this.temp.image === '') {
        this.temp.image = 'hasImage'
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.temp.image = ''
      }
    },
    handleExceed(file) {
      this.$message({
        message: '当前版本只支持上传一张图片！',
        type: 'warning'
      })
    },
    indexMethod(index) {
      return index + 1
    }
  }
}
</script>

<style scoped>
.image {
  width: 250px;
  height: 200px;
  border-radius: 5px;
  background-color: rgb(235,235,235);
  display:flex;
  justify-content: center;
  align-items: center;
}
</style>
